//
//  changPhoneNOViewController.m
//  孕妙
//
//  Created by 是源科技 on 16/4/20.
//  Copyright © 2016年 是源科技. All rights reserved.
//

#import "changPhoneNOViewController.h"

@interface changPhoneNOViewController ()
@property (nonatomic,strong)UITextField *oldPhoneTF;
@property (nonatomic,strong)UITextField *NewPhoneTF;
@property (nonatomic,strong)UITextField *yanzhengmaPhoneTF;
@property (nonatomic,strong)UIButton *yanzhengmaBtn;
@property (nonatomic,strong)UIButton *sureButton;

@property (nonatomic,copy)NSString *yzmString;
@property (nonatomic,strong)NSTimer *yzmTimer;
@property (nonatomic,assign)int yzmTime;

@end

@implementation changPhoneNOViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.title = @"更换手机号码";
    self.view.backgroundColor = YMColor(245, 245, 245);
    
    self.oldPhoneTF = [[UITextField alloc]init];
    self.NewPhoneTF = [[UITextField alloc]init];
    self.yanzhengmaPhoneTF = [[UITextField alloc]init];
    
    self.oldPhoneTF.keyboardType = UIKeyboardTypeDecimalPad;
    self.NewPhoneTF.keyboardType = UIKeyboardTypeDecimalPad;
    self.yanzhengmaPhoneTF.keyboardType = UIKeyboardTypeDecimalPad;
    
    
    CGFloat y = 85;
    
    for(int i = 1;i < 4;i ++)
    {
        UIView *view = [[UIView alloc]initWithFrame:CGRectMake(0, y, kDeviceWidth, 80)];
        view.backgroundColor = [UIColor whiteColor];
        view.tag = i;
        [self.view addSubview:view];
        
        
        y += view.frame.size.height;
        
        UILabel *label = [[UILabel alloc]initWithFrame:CGRectMake(0, y, kDeviceWidth, 1)];
        label.backgroundColor = YMColor(219, 219, 219);
        [self.view addSubview:label];
        y += 1;
        
        if(view.tag == 1)
        {
            [self addImageToView:view andImageName:@"Setting_phone" andTextField:self.oldPhoneTF andTFstr:@"请输入原手机号"];
        }
        if(view.tag == 2)
        {
            [self addImageToView:view andImageName:@"Setting_phone" andTextField:self.NewPhoneTF andTFstr:@"请输入新手机号"];
        }
        if(view.tag == 3)
        {
            [self addImageToView:view andImageName:@"Setting_Verification code" andTextField:self.yanzhengmaPhoneTF andTFstr:@"输入验证码"];
        }
    }
    
    y += 30;
    self.sureButton = [UIButton buttonWithType:UIButtonTypeCustom];
    self.sureButton.frame = CGRectMake(kDeviceWidth / 3.0, y, kDeviceWidth / 3.0, kDeviceWidth / 3.0 / 2.22);
    [self.sureButton setTitle:@"完  成" forState:UIControlStateNormal];
    [self.sureButton setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [self.sureButton setTitleColor:[UIColor grayColor] forState:UIControlStateHighlighted];
    self.sureButton.backgroundColor = YMColor(252, 160, 207);
    self.sureButton.layer.cornerRadius = 8.0;
    [self.view addSubview:self.sureButton];
    
    [self.sureButton addTarget:self action:@selector(clickSureButton) forControlEvents:UIControlEventTouchUpInside];
    
}

-(void)addImageToView:(UIView *)view andImageName:(NSString *)imageName andTextField:(UITextField *)TF andTFstr:(NSString *)tfStr
{
    CGFloat h = view.frame.size.height;
    UIImageView *logoImage = [[UIImageView alloc]initWithFrame:CGRectMake(35, h / 3.0, h / 3.0, h / 3.0)];
    logoImage.image = [UIImage imageNamed:imageName];
    [view addSubview:logoImage];
    if(view.tag == 3)
    {
        TF.frame = CGRectMake(kDeviceWidth / 4.0, 0, kDeviceWidth / 2.0, h);
        self.yanzhengmaBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        self.yanzhengmaBtn.frame = CGRectMake(kDeviceWidth / 3.0 * 2, h / 4.0, h / 2.0 * 2.375, h / 2.0);
        self.yanzhengmaBtn.layer.borderWidth = 1.0;
        self.yanzhengmaBtn.layer.cornerRadius = 5.0;
        self.yanzhengmaBtn.layer.borderColor = [YMColor(246, 156, 202)CGColor];
        [self.yanzhengmaBtn setTitle:@"获取验证码" forState:UIControlStateNormal];
        self.yanzhengmaBtn.titleLabel.font = [UIFont systemFontOfSize:13.0];
        [self.yanzhengmaBtn setTitleColor:YMColor(246, 156, 202) forState:UIControlStateNormal];
        [self.yanzhengmaBtn setTitleColor:[UIColor grayColor] forState:UIControlStateHighlighted];
        [view addSubview:self.yanzhengmaBtn];
        
        [self.yanzhengmaBtn addTarget:self action:@selector(clickYanzhengmaButton) forControlEvents:UIControlEventTouchUpInside];
    }
    else
    {
        TF.frame = CGRectMake(kDeviceWidth / 4.0, 0, kDeviceWidth / 4.0 * 3, h);
    }
    TF.placeholder = tfStr;
    [TF setValue:YMColor(201, 201, 201) forKeyPath:@"_placeholderLabel.textColor"];
    [view addSubview:TF];
}

-(void)shengchengYanZhengMa
{
    self.yzmString = [[NSString alloc]init];
    
    for(int i = 0;i < 6; i ++)
    {
        int m = arc4random() % 10;
        self.yzmString = [self.yzmString stringByAppendingString:[NSString stringWithFormat:@"%d",m]];
    }
    
    YMLog(@"随机生成的6位数位:%@",self.yzmString);
}

//点击验证码按钮
-(void)clickYanzhengmaButton
{
    
    NSUInteger phoneLength = self.NewPhoneTF.text.length;
    if(phoneLength == 11)
    {
        
        self.yzmTimer = [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(yamTimeDisplay) userInfo:nil repeats:YES];
        self.yzmTime = 60;
        self.yanzhengmaBtn.userInteractionEnabled = NO;
        [self shengchengYanZhengMa];
        NSString *urlString = @"http://web.cr6868.com/asmx/smsservice.aspx";
        NSURL *url = [[NSURL alloc]initWithString:urlString];
        NSMutableURLRequest *request = [[NSMutableURLRequest alloc]initWithURL:url cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:2];
        
        request.HTTPMethod = @"POST";
        NSString *str = [NSString stringWithFormat:@"name=13602624302&pwd=5E06798C36C5FA7CE3ACEA8DE233&content=验证码为%@，请在一分钟内输入正确的验证码&mobile=%@&stime=&sign=是源医学&type=pt&extno=",self.yzmString,self.NewPhoneTF.text];
        NSData *data = [str dataUsingEncoding:NSUTF8StringEncoding];
        [request setHTTPBody:data];
        
        NSOperationQueue *queue = [NSOperationQueue mainQueue];
        
        [NSURLConnection sendAsynchronousRequest:request queue:queue completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError)
         {
             
             if (data)
             {
                 // 请求成功
                 NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableLeaves error:nil];
                 YMLog(@"yanzhengmadict = %@",dict);
                 [MBProgressHUD showSuccess:@"验证码发送成功!"];
                 
                 
             }
             else
             {
                 self.yanzhengmaBtn.userInteractionEnabled = YES;
             }
             
         }];
    }
    else
    {
        [MBProgressHUD showError:@"请输入正确的手机号"];
    }
}
//验证码倒计时
-(void)yamTimeDisplay
{
    self.yzmTime --;
    if(self.yzmTime > 0)
    {
        self.yanzhengmaBtn.backgroundColor = [UIColor whiteColor];
        [self.yanzhengmaBtn setTitle:[NSString stringWithFormat:@"%ds",self.yzmTime] forState:UIControlStateNormal];
        [self.yanzhengmaBtn setTintColor:[UIColor whiteColor]];
        self.yanzhengmaBtn.userInteractionEnabled = NO;
    }
    else
    {
        [self.yanzhengmaBtn setTitle:@"获取验证码" forState:UIControlStateNormal];
        [self.yanzhengmaBtn setTitleColor:YMColor(249, 137, 196) forState:UIControlStateNormal];
        self.yanzhengmaBtn.layer.cornerRadius = 5.0;
        [self.yanzhengmaBtn setBackgroundColor:[UIColor clearColor]];
        self.yanzhengmaBtn.userInteractionEnabled = YES;
        [self.yzmTimer invalidate];
        self.yzmTimer = nil;
        self.yzmString = nil;
    }
    
}
//完成按钮
-(void)clickSureButton
{
    if(![self.oldPhoneTF.text isEqualToString:@""])
    {
        if(![self.NewPhoneTF.text isEqualToString:@""])
        {
            if([self.yanzhengmaPhoneTF.text isEqualToString:self.yzmString])
            {
                NSString *urlString = @"http://120.24.178.16:8080/Health/baby/updateUserInfo.do";
                NSURL *url = [[NSURL alloc]initWithString:urlString];
                NSMutableURLRequest *request = [[NSMutableURLRequest alloc]initWithURL:url cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:2];
                
                request.HTTPMethod = @"POST";
                NSString *str = [NSString stringWithFormat:@"account=%@&type=0&info=%@",self.oldPhoneTF.text,self.NewPhoneTF.text];
                NSData *data = [str dataUsingEncoding:NSUTF8StringEncoding];
                [request setHTTPBody:data];
                
                NSOperationQueue *queue = [NSOperationQueue mainQueue];
                
                [NSURLConnection sendAsynchronousRequest:request queue:queue completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError)
                 {
                     if (data)
                     {
                         // 请求成功
                         NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableLeaves error:nil];
                         //                         YMLog(@"dict = %@",dict);
                         if([[dict objectForKey:@"code"] isEqualToString:@"0"])
                         {
                             [self.yzmTimer invalidate];
                             self.yzmTimer = nil;
                             
                             self.yanzhengmaBtn.backgroundColor = [UIColor clearColor];
                             [self.yanzhengmaBtn setTitle:@"获取验证码" forState:UIControlStateNormal];
                             self.yanzhengmaBtn.userInteractionEnabled = YES;
                             [MBProgressHUD showSuccess:@"更改手机成功"];
                             [[NSUserDefaults standardUserDefaults]setObject:self.NewPhoneTF.text forKey:@"userAccount"];
                             dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                                 [self.navigationController popToRootViewControllerAnimated:YES];
                             });
                         }
                         if([[dict objectForKey:@"code"] isEqualToString:@"1"])
                         {
                             [MBProgressHUD showError:@"更新失败！"];
                         }
                         if([[dict objectForKey:@"code"] isEqualToString:@"2"])
                         {
                             [MBProgressHUD showError:@"缺少参数！"];
                         }
                         if([[dict objectForKey:@"code"] isEqualToString:@"3"])
                         {
                             [MBProgressHUD showError:@"用户不存在！"];
                         }
                     }
                 }];
                
            }
            else
            {
                [MBProgressHUD showError:@"验证码错误"];
            }
        }
        else
        {
            [MBProgressHUD showError:@"新手机号为空"];
        }
    }
    else
    {
        [MBProgressHUD showError:@"原手机号为空"];
    }
    
}


@end
